﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Threading;
using System.Windows.Threading;
using System.IO.IsolatedStorage;
using Microsoft.Phone.Net.NetworkInformation;

namespace BattleAuth
{
    public enum ErrorType
    {
        NoInternet,
        Enrolling
    }
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Set the data context of the listbox control to the sample data
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            error_Enrolling.Visibility = System.Windows.Visibility.Collapsed;
            error_NoInternet.Visibility = System.Windows.Visibility.Collapsed;
            if (BattleAuthenticator.InternetIsAvailable() == false)
            {
                ShowError(ErrorType.NoInternet);
            }
            else
            {
                syncTimer = new DispatcherTimer();
                syncTimer.Tick += new EventHandler(syncTimer_Tick);
                syncTimer.Interval = new TimeSpan(0, 0, 1);
                syncTimer.Start();
            }
        }
        private void ShowError(ErrorType et)
        {
            if (et == ErrorType.NoInternet)
            {
                error_NoInternet.Visibility = System.Windows.Visibility.Visible;
            }
            else if (et == ErrorType.Enrolling)
            {
                error_Enrolling.Visibility = System.Windows.Visibility.Visible;
            }
        }
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            
        }
        private DispatcherTimer syncTimer;
        private DateTime m_nextRefresh;
        public DateTime NextRefresh
        {
            get
            {
                return m_nextRefresh;
            }
            set
            {
                m_nextRefresh = value;
            }
        }

        private DateTime m_codeDisplayed;
        /// <summary>
        /// Get/set time code was last displayed
        /// </summary>
        public DateTime CodeDisplayed
        {
            get
            {
                return m_codeDisplayed;
            }
            set
            {
                m_codeDisplayed = value;
            }
        }
        private void syncTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                if (BattleAuthenticator.InternetIsAvailable() == false)
                {
                    ShowError(ErrorType.NoInternet);
                    return;
                }
                else
                {
                    error_NoInternet.Visibility = System.Windows.Visibility.Collapsed;
                }

                string code = App.Auth.GetCode();
                tbCode.Text = code;
                tbSerial.Text = App.Auth.Serial;
                if (App.Auth.IsEnrolling)
                {
                    ShowError(ErrorType.Enrolling);
                    return;
                }
                else
                {
                    error_Enrolling.Visibility = System.Windows.Visibility.Collapsed;
                }

                panControl.Visibility = System.Windows.Visibility.Visible;

                DateTime now = DateTime.Now;

                if (pbar.Visibility == System.Windows.Visibility.Visible)
                {
                    int tillUpdate = (int)((App.Auth.ServerTime % 30000L) / 1000L);
                    pbar.Value = tillUpdate;
                    if (tillUpdate == 0)
                    {
                        NextRefresh = now;
                    }
                }
                if (App.Auth != null && now >= NextRefresh)
                {
                    NextRefresh = now.AddSeconds(30);
                    DisplayCode();
                }
            }
            catch (Exception ex)
            {
                panControl.Visibility = System.Windows.Visibility.Collapsed;
            }
        }
        private void DisplayCode()
        {
            if (App.Auth.IsEnrolling == false)
            {
                string code = App.Auth.GetCode();
                tbCode.Text = code;
                tbSerial.Text = App.Auth.Serial;
                CodeDisplayed = DateTime.Now;
                LoadInfo();
                error_Enrolling.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                ShowError(ErrorType.Enrolling);
            }
            syncTimer.Start();
        }
        private void LoadInfo()
        {
            if (App.Auth.IsEnrolling == false)
            {
                infoAdv_ServerTimeDiff.Text = App.Auth.ServerTimeDifference.ToString();
                infoAdv_Serial.Text = App.Auth.Serial;
                infoAdv_SecretKey.Text = BattleAuthenticator.ConvertToString(App.Auth.SecretKey);
                infoAdv_SecretData.Text = App.Auth.SecretData;
            }
        }

        private void btnSync_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            App.Auth.Synchronise();
        }

        private void btnNewSerial_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            App.Auth = new BattleAuthenticator();
            ShowError(ErrorType.Enrolling);
            App.Auth.Enroll();
            
            DisplayCode();
            error_Enrolling.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void btnCopy_Click(object sender, System.Windows.RoutedEventArgs e)
        {

        }
    }
}